﻿using DotNetty.Transport.Bootstrapping;
using DotNetty.Transport.Channels.Sockets;
using DotNetty.Transport.Channels;
using System.Net;
using DotNetty.Handlers.Logging;
using DotNetty.Codecs;
using System.Text;

namespace IdleTestClient
{
    internal class Program
    {
        static async Task RunClientAsync()
        {
            var group = new MultithreadEventLoopGroup();

            try
            {
                Bootstrap bootstrap = new Bootstrap();
                bootstrap.Group(group)
                    .Channel<TcpSocketChannel>()
                    .Option(ChannelOption.TcpNodelay, true) // Option设置底层参数,这里设置基于TCP的socket它是没有延迟的
                    .Handler(new ActionChannelInitializer<ISocketChannel>(channel =>
                    {
                        IChannelPipeline pipeline = channel.Pipeline;
                        pipeline.AddLast(new StringDecoder(Encoding.UTF8), new StringEncoder(Encoding.UTF8));
                        pipeline.AddLast(new LoggingHandler(LogLevel.DEBUG));
                    }));

                IChannel bootstrapChannel = await bootstrap.ConnectAsync(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8888));

                for (; ; )
                {
                    Console.WriteLine("请输入给服务端发送的内容:");
                    await bootstrapChannel.WriteAndFlushAsync(Console.ReadLine());
                }

                await bootstrapChannel.CloseAsync();
                Console.ReadKey();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Task.WaitAll(group.ShutdownGracefullyAsync());
            }
        }

        static async Task Main(string[] args) => await RunClientAsync();
    }
}